// stores/useModelStore.ts
import { defineStore } from 'pinia'
import {useConfigStore} from '../stores/configStore'
import myRequest from '@renderer/utils/request'
import { ElMessage } from 'element-plus'

interface SdModel {
  title: string
  model_name: string
  hash: string
  filename: string
}

export const useModelStore = defineStore('models', {
  state: () => ({
    currentModel: '',
    outputPath: '',
    modelList: [] as SdModel[],
    loading: false,
  }),
  actions: {
    async fetchModels() {
      const {config} = useConfigStore()
      this.loading = true
      try {
        if(config.sdEngine =='webui'){
          myRequest.get(`${config.sdwebuiPath}v1/sd-models`).then(res => {
          if(Array.isArray(res.data)){
            this.modelList = res.data
            if (this.modelList.length > 0) {
              const filePath = this.modelList[0].filename
              const parts = filePath.replace(/\//g, '\\').split('\\')
              const modelsIndex = parts.findIndex(p => p.toLowerCase() === 'models')
              if (modelsIndex === -1) {
                this.outputPath = ""
              }
              else{
                this.outputPath = `${parts.slice(0, modelsIndex).join('\\')}\\outputs\\txt2img-images`
              }
            }
            ElMessage.success('模型列表获取成功')
          }
        })
        myRequest.get(`${config.sdwebuiPath}v1/options`).then(res => {
          if (res.data.sd_model_checkpoint) {
            this.currentModel = res.data.sd_model_checkpoint
          }
          ElMessage.success('当前模型信息获取成功')
        })
        }
        else if(config.sdEngine =='comfyui'){
          const res = await myRequest.get(`${config.comfyuiPath}object_info`);
          const checkpointNode = res.data.CheckpointLoaderSimple;
          if (checkpointNode) {
            this.modelList = checkpointNode.input.required.ckpt_name[0].map(name => ({
              title: name,
              model_name: name,
              filename: name,
            }));
            if(this.currentModel){
              if(!this.modelList.find(item=> item.model_name == this.currentModel)){
                this.currentModel = this.modelList[0].model_name;
              }
            }
            else{
              this.currentModel = this.modelList[0].model_name;
            }
          }
        }
      } finally {
        this.loading = false
      }
    },
    async updateModel(value: string) {
      const {config} = useConfigStore()
      this.loading = true
      if(config.sdEngine =='webui'){
         myRequest({ url: config.sdwebuiPath + 'v1/options', method: 'post', data: { sd_model_checkpoint: value }, headers: { 'Content-Type': 'application/json' } }).then(res => {
          ElMessage.success(JSON.stringify(res.data))
          this.currentModel = value
      }).finally(() => {
          this.loading = false
      }).catch(err => {
          ElMessage.error(err.message)
      })
      }
      else if(config.sdEngine =='comfyui'){
        this.currentModel = value;
        this.loading = false
      }
    }
  }
})
